#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import telnetlib
import logging


class WowRemoteCommander:
    def __init__(self, host, port, username, password):
        """
        WOW远程访问类，用于远程执行游戏内命令，达到远程监控、操作游戏的目的

        Args:
            host (str): 服务端地址
            port (str): 远程端口
            username (str): GM 账号
            password (str): GM 账号密码
        """
        self.host = host
        self.port = port
        self.username = username
        self.password = password

    def command(self, command):
        tn = telnetlib.Telnet(self.host, self.port)

        logging.info("[WoWRemote] - Execute Command %s!", command)

        # tn.set_debuglevel(5) #this is to print the logs of the connection via telnet

        tn.read_until("Username: ")
        tn.write(self.username + "\r\n")
        tn.read_until("Password: ")
        tn.write(self.password + "\r\n")
        tn.read_until("AC")
        tn.write(str(command) + "\r\n")
        tn.write("exit" + "\r\n")

        read = tn.read_all()

        if command == ".ticket list" or ".ticket viewid " in command or ".ticket onlinelist" in command:
            read = read.replace("|cffaaffaa", "")
            read = read.replace("|r", "")
            read = read.replace("|cffaaccff", "")
            read = read.replace("|cff00ff00", "")
            read = read.replace("|cff00ccff", "")

        tn.close()

        logging.info("[WoWRemote] - command return msg %s!", read)

        read = read.decode('utf-8')

        return read[2:read.find('AC>')]
